<template>
  <view class="container">
    <!-- 地图区域 -->
    <view class="map-container">
      <map
        id="map"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="16"
        :show-location="true"
        @markertap="handleMarkerTap"
        :enable-rotate="true"
        :enable-zoom="true"
        :enable-scroll="true"
        :enable-3D="true"
        :show-compass="true"
        :show-scale="true"
      ></map>
      
      <!-- 地图控制按钮 -->
      <view class="map-controls">
        <button class="control-btn" @click="handleLocation">
          <image class="icon" src="/static/icons/location.svg" mode="aspectFit"></image>
        </button>
      </view>
    </view>

    <!-- 位置选择列表（固定高度，直接滚动） -->
    <view class="location-list-fixed">
      <view class="list-header">
        <view class="search-box">
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索位置"
            class="search-input"
          />
          <button class="search-btn" @click="handleSearch">
            <image class="search-icon" src="/static/icons/search.svg" mode="aspectFit"></image>
            搜索
          </button>
        </view>
      </view>

      <scroll-view scroll-y class="location-scroll-fixed" :scroll-top="0">
        <!-- 当前位置信息 -->
        <view class="current-location">
          <view class="location-header">
            <text class="title">当前位置</text>
          </view>
          <view class="location-info" @click="selectCurrentLocation">
            <view class="location-details">
              <text class="address">{{ currentAddress }}</text>
              <text class="coordinates">纬度: {{ latitude.toFixed(6) }}, 经度: {{ longitude.toFixed(6) }}</text>
            </view>
            <view class="select-btn">
              <text class="select-text">选择</text>
            </view>
          </view>
        </view>

        <!-- 附近售货机 -->
        <view v-if="vendingMachines.length > 0" class="machines-section">
          <view class="section-header">
            <text class="title">附近售货机</text>
            <text class="count">({{ vendingMachines.length }})</text>
          </view>
          <view 
            v-for="machine in vendingMachines" 
            :key="machine.deviceId"
            class="machine-item"
            @click="selectMachine(machine)"
          >
            <view class="machine-info">
              <text class="machine-name">{{ machine.deviceName }}</text>
              <text class="machine-address">{{ machine.address || '未知地址' }}</text>
              <text class="machine-distance">距离: {{ machine.distance }}km</text>
            </view>
            <view class="select-btn">
              <text class="select-text">选择</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else-if="!isLoading" class="empty-state">
          <text class="empty-text">暂无附近售货机</text>
          <text class="empty-tip">请尝试搜索其他位置</text>
        </view>
      </scroll-view>
    </view>
    
    <Loading :show="isLoading" />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import * as mapApi from '@/api/map';
import { getDeviceDetail } from '@/api/device';
import Loading from '@/components/Loading.vue';

// 响应式数据
const isLoading = ref(false);
const latitude = ref(30.572815);
const longitude = ref(104.066803);
const currentAddress = ref('正在获取位置...');
const searchKeyword = ref('');
const vendingMachines = ref<any[]>([]);
const markers = ref<any[]>([]);
const isListExpanded = ref(false);
const selectedLocation = ref<{
  latitude: number;
  longitude: number;
  address: string;
  type: 'location' | 'machine';
  machineInfo?: any;
} | null>(null);

// 页面参数
const pageParams = ref<{
  from?: string;
  callback?: string;
}>({});

// 地图上下文
let mapContext: any = null;

// 计算两点之间的距离
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
  if (!lat1 || !lon1 || !lat2 || !lon2) {
    console.log('距离计算参数无效：', { lat1, lon1, lat2, lon2 });
    return 0;
  }
  
  const R = 6378137; // 地球半径，单位米
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  
  // 转换为公里，保留一位小数
  const distanceInKm = Number((distance / 1000).toFixed(1));
  console.log('距离计算结果：', {
    from: { lat: lat1, lon: lon1 },
    to: { lat: lat2, lon: lon2 },
    distance: distanceInKm
  });
  return distanceInKm;
};

// 页面加载
onMounted(async () => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage.options) {
    pageParams.value = currentPage.options;
  }
  
  // 初始化地图上下文
  mapContext = uni.createMapContext("map");
  
  // 获取当前位置
  try {
    isLoading.value = true;
    await getCurrentLocation();
    // 获取周边售货机
    await getNearbyMachines();
  } catch (error) {
    console.error('初始化失败:', error);
    uni.showToast({
      title: '位置获取失败，请手动搜索',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
});

// 检查位置权限
const checkLocationPermission = () => {
  return new Promise((resolve, reject) => {
    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        resolve(true);
      },
      fail: () => {
        uni.showModal({
          title: '提示',
          content: '需要获取您的位置信息，是否授权？',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    resolve(true);
                  } else {
                    reject(new Error('用户拒绝授权位置信息'));
                  }
                },
                fail: () => {
                  reject(new Error('打开设置页面失败'));
                }
              });
            } else {
              reject(new Error('用户拒绝授权位置信息'));
            }
          }
        });
      }
    });
  });
};

// 获取当前位置
const getCurrentLocation = async () => {
  try {
    // 先尝试GPS定位
    try {
      await checkLocationPermission();
      
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: "gcj02",
          success: async (res) => {
            latitude.value = res.latitude;
            longitude.value = res.longitude;
            
            // 获取地址信息
            try {
              const response = await mapApi.regeocode(res.longitude, res.latitude);
              if (response.code === 200 && response.data) {
                currentAddress.value = response.data.formattedAddress || '未知地址';
              } else {
                currentAddress.value = `纬度: ${res.latitude.toFixed(6)}, 经度: ${res.longitude.toFixed(6)}`;
              }
            } catch (error) {
              console.error('获取地址失败:', error);
              currentAddress.value = `纬度: ${res.latitude.toFixed(6)}, 经度: ${res.longitude.toFixed(6)}`;
            }
            
            resolve(true);
          },
          fail: (error) => {
            console.error('GPS定位失败:', error);
            reject(error);
          }
        });
      });
    } catch (error) {
      console.error('GPS定位失败，尝试IP定位:', error);
      
      // GPS定位失败，使用IP定位
      const response = await mapApi.getLocationByIp();
      
      if (response.code === 200 && response.data) {
        const data = response.data;
        
        if (data.latitude && data.longitude) {
          latitude.value = parseFloat(data.latitude);
          longitude.value = parseFloat(data.longitude);
          currentAddress.value = data.formattedAddress || data.address || '未知地址';
        } else if (data.rectangle) {
          const coords = data.rectangle.split(';')[0].split(',');
          longitude.value = parseFloat(coords[0]);
          latitude.value = parseFloat(coords[1]);
          currentAddress.value = data.formattedAddress || data.address || '未知地址';
        } else {
          throw new Error('IP定位返回数据格式错误');
        }
      } else {
        throw new Error('IP定位失败');
      }
    }
  } catch (error) {
    console.error('所有定位方式都失败:', error);
    // 使用默认位置
    currentAddress.value = '位置获取失败，请手动搜索';
    throw error;
  }
};

// 获取周边售货机
const getNearbyMachines = async () => {
  try {
    const result = await mapApi.searchAround(longitude.value, latitude.value, '', 5);
	console.log(result)
    if (result.data) {
      // 并发获取详细信息
      const machinesWithDetail = await Promise.all(result.data.map(async (device: any) => {
        const deviceLat = Number(device.location?.latitude || device.location?.lat);
        const deviceLon = Number(device.location?.longitude || device.location?.lon);
        // 计算距离
        const distance = calculateDistance(
          latitude.value,
          longitude.value,
          deviceLat,
          deviceLon
        );
        let detail = null;
        try {
          const res = await getDeviceDetail(Number(device.deviceId), 1);
          detail = res.data;
        } catch (e) {
          detail = null;
        }
        // 优先用详细信息的siteName/location.address
        let address = device.address || '未知地址';
        if (detail) {
          address = detail.siteName || detail.location?.address || address;
        }
        return {
          deviceId: device.deviceId,
          deviceName: device.deviceName || (detail ? detail.deviceName : '自助售货机'),
          address,
          distance: distance.toFixed(2),
          status: device.status || (detail ? detail.status : 1),
          location: {
            latitude: deviceLat,
            longitude: deviceLon
          }
        };
      }));
      vendingMachines.value = machinesWithDetail;
      // 更新地图标记
      updateMarkers();
    }
  } catch (error) {
    console.error('获取周边售货机失败:', error);
  }
};

// 更新地图标记
const updateMarkers = () => {
  markers.value = vendingMachines.value.map((machine, index) => ({
    id: machine.deviceId,
    latitude: machine.location.latitude,
    longitude: machine.location.longitude,
    title: machine.deviceName,
    iconPath: "/static/marker.png",
    width: 32,
    height: 42,
    callout: {
      content: `${machine.deviceName}\n${getStatusText(machine.status)}`,
      color: "#000000",
      fontSize: 14,
      borderRadius: 4,
      bgColor: "#ffffff",
      padding: 8,
      display: "ALWAYS",
    },
  }));
};

// 处理标记点击
const handleMarkerTap = (e: any) => {
  const marker = markers.value.find((m) => m.id === e.markerId);
  if (marker) {
    const machine = vendingMachines.value.find(m => m.deviceId === marker.id);
    if (machine) {
      selectMachine(machine);
    }
  }
};

// 选择当前位置
const selectCurrentLocation = () => {
  selectedLocation.value = {
    latitude: latitude.value,
    longitude: longitude.value,
    address: currentAddress.value,
    type: 'location'
  };
  // 存入本地缓存，带时间戳
  uni.setStorageSync('selectedLocation', {
    ...selectedLocation.value,
    _ts: Date.now()
  });
  uni.navigateBack();
};

// 选择售货机
const selectMachine = (machine: any) => {
  // 更新地图中心点到选中的售货机位置
  latitude.value = machine.location.latitude;
  longitude.value = machine.location.longitude;
  currentAddress.value = machine.address || currentAddress.value;
  
  selectedLocation.value = {
    latitude: machine.location.latitude,
    longitude: machine.location.longitude,
    address: machine.address || currentAddress.value,
    type: 'machine',
    machineInfo: machine
  };
  // 存入本地缓存，带时间戳
  uni.setStorageSync('selectedLocation', {
    ...selectedLocation.value,
    _ts: Date.now()
  });
  uni.navigateBack();
};

// 处理搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: '搜索中...'
    });

    // 使用 geocode 获取地址的经纬度
    const geocodeResult = await mapApi.geocode(searchKeyword.value);
    if (geocodeResult.data && geocodeResult.data.latitude && geocodeResult.data.longitude) {
      const { latitude: newLatitude, longitude: newLongitude } = geocodeResult.data;

      // 更新地图中心点
      latitude.value = newLatitude;
      longitude.value = newLongitude;
      
      // 移动地图到搜索位置
      const mapContext = uni.createMapContext("map");
      mapContext.moveToLocation({
        latitude: newLatitude,
        longitude: newLongitude,
      });

      // 获取搜索位置的地址
      try {
        const response = await mapApi.regeocode(newLongitude, newLatitude);
        if (response.code === 200 && response.data) {
          currentAddress.value = response.data.formattedAddress || '未知地址';
        }
      } catch (error) {
        console.error('获取地址失败:', error);
        currentAddress.value = `纬度: ${newLatitude.toFixed(6)}, 经度: ${newLongitude.toFixed(6)}`;
      }

      // 搜索周边售货机
      await getNearbyMachines();
      
      // 展开列表
      isListExpanded.value = true;
    } else {
      uni.showToast({
        title: '未找到相关位置',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索失败：', error);
    uni.showToast({
      title: '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 处理定位按钮
const handleLocation = async () => {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '定位中...'
    });

    // 获取当前位置
    await getCurrentLocation();
    
    // 获取周边售货机
    await getNearbyMachines();
    
    // 展开列表
    isListExpanded.value = true;
    
    uni.showToast({
      title: '定位成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('定位失败:', error);
    uni.showToast({
      title: '定位失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '离线';
    case 2:
      return '在线';
    case 3:
      return '维护中';
    default:
      return '未知';
  }
};

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 2: return 'status-online';
    case 1: return 'status-offline';
    case 3: return 'status-error';
    case 4:
    case 5: return 'status-maintenance';
    default: return 'status-offline';
  }
};

// 页面卸载
onUnmounted(() => {
  mapContext = null;
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}

.map-controls {
  position: absolute;
  right: 30rpx;
  bottom: 50%;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  z-index: 100;
}

.control-btn {
  width: 88rpx;
  height: 88rpx;
  background-color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  padding: 0;
  margin: 0;
  line-height: 1;
}

.control-btn:active {
  background-color: #f0f0f0;
}

.control-btn .icon {
  width: 40rpx;
  height: 40rpx;
}

/* 位置选择列表（固定高度，直接滚动） */
.location-list-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 30rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  z-index: 99;
  height: 45vh;
}

.location-scroll-fixed {
  height: calc(35vh - 100rpx); /* header高度100rpx，如需调整请修改 */
  overflow-y: auto;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.search-box {
  flex: 1;
  display: flex;
  gap: 20rpx;
  margin-right: 20rpx;
}

.search-input {
  flex: 1;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
}

.search-btn {
  width: 140rpx;
  height: 80rpx;
  background-color: #007aff;
  color: #ffffff;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.search-btn:active {
  background-color: #0062cc;
}

.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.current-location {
  margin-bottom: 30rpx;
}

.location-header {
  margin-bottom: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.location-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background: #f8f8f8;
  border-radius: 16rpx;
}

.location-details {
  flex: 1;
}

.address {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
}

.coordinates {
  display: block;
  font-size: 24rpx;
  color: #666666;
}

.select-btn {
  padding: 15rpx 30rpx;
  background: #007aff;
  color: #ffffff;
  border-radius: 25rpx;
  font-size: 24rpx;
}

.select-text {
  font-size: 24rpx;
}

.machines-section {
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.count {
  font-size: 24rpx;
  color: #666666;
}

.machine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.machine-info {
  flex: 1;
}

.machine-name {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
}

.machine-address {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 10rpx;
}

.machine-distance {
  display: block;
  font-size: 24rpx;
  color: #007aff;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  display: block;
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 10rpx;
}

.empty-tip {
  display: block;
  font-size: 24rpx;
  color: #999999;
}
</style>